let app = getApp();
import Dialog from '../../../dist/dialog/dialog';
import util from "../../../utils/util";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    keyWord:'',
    tabIndex:0,
    status:4,
    timer: '',
    tabList:[
      {
        status:4,
        index:0,
        name:'全部',
        goodsList:[],
        page:1
      },
      {
        status:0,
        index:1,
        name:'待付款',
        goodsList:[],
        page:1
      },
      {
        status:1,
        index:2,
        name:'待使用',
        goodsList:[],
        page:1
      },
      {
        status:3,
        index:3,
        name:'已使用',
        goodsList:[],
        page:1
      },
      {
        status:-1,
        index:4,
        name:'退款/售后',
        goodsList:[],
        page:1
      }
    ],
    orderLastPage:0,
    isLoadMore: true,
    storeApiArr:['plugin.coupon-store.frontend.order-list.index','plugin.coupon-store.frontend.order-list.waitPay','plugin.coupon-store.frontend.order-list.waitSend',
    'plugin.coupon-store.frontend.order-list.completed', 'plugin.coupon-store.frontend.order-list.refund']
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if((options.status??'') !== '') {
     for(let i in this.data.tabList) { //跳转到对应的状态
       if(this.data.tabList[i].status === Number(options.status)) {
         this.setData({tabIndex: this.data.tabList[i].index})
       }
     }
    }
    
  },
  storeGoodsList() {
    let api = this.data.storeApiArr[this.data.tabIndex];
    let urlStr = app.getNetAddresss(api);
    let json = {
      page: this.data.tabList[this.data.tabIndex].page,
      keyword: this.data.keyWord
    };
    app._postNetWork({
      url: urlStr,
      data:json,
      success:  (resdata) => {
        let res = resdata.data;
        wx.hideLoading();
        wx.hideNavigationBarLoading();//隐藏导航条加载动画
        //停止下拉刷新
        wx.stopPullDownRefresh();
        if (res.result == 1) {
          this.data.isLoadMore = true;
          this.data.orderLastPage = res.data.last_page;
          if (!this.data.orderLastPage) {
            this.data.orderLastPage = 0;
          }
          let tabIndex = this.data.tabIndex;
          let item = this.data.tabList[tabIndex].goodsList;
          this.setData({
            ["tabList[" + tabIndex + "].goodsList"]: res.data.data
          })
        } else {
          this.data.storePage = this.data.storePage - 1;
          this.data.isLoadMore = false;
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  getMoreData() {
    this.data.isLoadMore = false; // 防止多次请求分页数据
    if (this.data.tabList[this.data.tabIndex].page >= this.data.orderLastPage) {
      return;
    } else {
      this.data.tabList[this.data.tabIndex].page +=  1;
      let api = this.data.storeApiArr[this.data.tabIndex];
      console.log(api);
      let urlStr = app.getNetAddresss(api);
      let json = {
        page: this.data.tabList[this.data.tabIndex].page,
        keyword: this.data.keyWord
      };
      app._getNetWork({
        url: urlStr,
        data: json,
        success: (resdata) => {
          let res = resdata.data;
          let list = res.data.data;
          if (res.result == 1) {
            this.data.isLoadMore = true;
            let tabIndex = this.data.tabIndex;
            this.setData({
              ["tabList[" + tabIndex + "].goodsList"]: this.data.tabList[tabIndex].goodsList.concat(list),
            })
          } else {
            this.data.page = this.data.page - 1;
            this.data.isLoadMore = false;
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1500
            });
          }
        },
        fail: function (res) {
          console.log(res);
        }
      });
    }
  },
  onOrderChange(event) {
    this.setData({
      tabIndex: event.detail.name
    })
    if(this.data.tabList[this.data.tabIndex].goodsList.length === 0) {
      this.storeGoodsList();
    }
    
  },
  orderSearch({ detail }) {
    console.log(detail);

      this.setData({ keyWord: detail });
      // 防抖
      if (this.timer) clearTimeout(this.timer);
      this.timer = setTimeout(() => {
        util.debounce(this.storeGoodsList());
      }, 500);
    
  },
  orderstateOn(event) {
    const e = event.currentTarget.dataset,
          value = e.value,
          id = e.id,
          goodsId = e.goodsid,
          refundId = e.refundid,
          api = e.api,
          storename = e.storename;
    this.getorderState({value,id,goodsId,refundId,api,storename});
  },
  getorderState(...args) {
    let {value,id,goodsId,refundId,api,storename} = {...args[0]};
    let query = {
      'coupon_store_order_detail': `/packageF/consumption/orderDetails/orderDetails?orderId=${id}`, //订单详情
      'coupon_store_refund_page': `/packageF/consumption/refundOrder/refundOrder?orderId=${id}&type=2`, //申请售后
      1: `/packageD/buy/orderPay/orderPay?order_id=${id}&status=2`, //支付
      41:  `${api}`, //客服
      'coupon_store_comment': `/packageF/consumption/evaluate/evaluate?orderId=${id}&storeName=${storename}`, //评价
      'coupon_store_rebuy': `/packageF/consumption/goodsDetails/goodsDetails?goodsId=${goodsId}`,  //商品详情
      'coupon_store_refunding':  `/packageF/consumption/refundProcess/refundProcess?refundId=${refundId}`, //售后详情
      'coupon_store_refunded':  `/packageF/consumption/refundProcess/refundProcess?refundId=${refundId}`
    }
    if(value.toString() === '9' || value.toString() === '12') {
      Dialog.confirm({
        title: '提示',
        message: value===9? '确定取消该订单?':'确定删除该订单?',
      }).then(() => {
        // on close
        value===9?this.cancelPay(id,api):this.deletePay(id,api);
      })
      .catch(() => {
        // on cancel
      });  //删除订单
    } else {
      return wx.navigateTo({
        url: query[value]
      });
    }
  },
  cancelPay(id,api) {
    let urlStr = app.getNetAddresss(api);
    let json = {
      order_id:id
    };
    app._postNetWork({
      url: urlStr,
      data:json,
      success:  (resdata) => {
        let res = resdata.data;
        if (res.result == 1) {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
          this.storeGoodsList();
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  deletePay(id,api) {
    let urlStr = app.getNetAddresss(api);
    let json = {
      order_id:id
    };
    app._postNetWork({
      url: urlStr,
      data:json,
      success:  (resdata) => {
        let res = resdata.data;
        if (res.result == 1) {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
          this.storeGoodsList();
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  ondetails(event) {
    let id = event.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/packageF/consumption/orderDetails/orderDetails?orderId=${id}`
    });
  },
    

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.storeGoodsList();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    let tabIndex = this.data.tabIndex;
    wx.showNavigationBarLoading();
     //显示 loading 提示框。需主动调用 wx.hideLoading 才能关闭提示框
     wx.showLoading({
      title: '刷新中...',
    })
    this.setData({
      ["tabList[" + tabIndex + "].page"]: 1
    })
    console.log(this.data.tabList[this.data.tabIndex].page);
    this.storeGoodsList();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (this.data.isLoadMore) {
      this.getMoreData();
    } else {
      console.log('没有更多了');
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})